package com.boyiis.sell.controller;

import com.boyiis.sell.constant.CookieConstant;
import com.boyiis.sell.constant.RedisConstant;
import com.boyiis.sell.enums.ResultEnum;
import com.boyiis.sell.model.entity.Seller;
import com.boyiis.sell.service.SellerService;
import com.boyiis.sell.utils.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/seller")
public class SellerController {

    @Autowired
    private SellerService sellerService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/login")
    public ModelAndView login(@RequestParam("openid") String openid, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        //1.openid去和数据库里的数据匹配
        Seller seller = sellerService.findByOpenid(openid);
        if (null == seller) {
            map.put("msg", ResultEnum.WX_LOGIN_FAIL.getMsg());
            map.put("url", "/sell/seller/order/list");
            return new ModelAndView("common/error", map);
        }

        //2.设置token至redis
        String token = UUID.randomUUID().toString();
        Integer expire = RedisConstant.EXPIRE;//过期时间
        stringRedisTemplate.opsForValue().set(String.format(RedisConstant.TOKEN_PREFIX, token), openid, expire, TimeUnit.SECONDS);

        //3.设置token至cookie
        CookieUtil.set(response, CookieConstant.TOKEN, token, expire);

        return  new ModelAndView("redirect:/sell/seller/order/list");
    }

    @GetMapping("/logout")
    public ModelAndView logout( HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        //1.从cookie中查询
       Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);

       if(null != cookie){
           //2.清除redis
           stringRedisTemplate.opsForValue().getOperations().delete(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));

           //3.清除cookie
           CookieUtil.set(response, CookieConstant.TOKEN, null, 0);
       }

        map.put("msg", ResultEnum.WX_LOGOUT_SUCCESS.getMsg());
        map.put("url", "/sell/seller/order/list");
        return  new ModelAndView("common/success", map);

    }
}
